package com.lwd.controller;

import java.io.IOException;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import com.github.pagehelper.PageInfo;
import com.lwd.entity.*;
import com.lwd.mapper.GoodsMapper;
import com.lwd.service.TypeService;
import com.lwd.utils.ResultEntity;
import com.lwd.utils.UploadFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lwd.service.GoodsService;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private OSSProperties ossProperties;

    @ResponseBody
    @RequestMapping("getAllGoods")
    public List<Goods> getAllGoods(Model model) {

        List<Goods> goodsList = goodsService.getAllGoods();

        //model.addAttribute("goodsList", goodsList);

        return goodsList;
    }

    @RequestMapping("getAllGoodsMutiFunction")
    public String getAllGoodsMutiFunction(

            // 使用@RequestParam注解的defaultValue属性，指定默认值，在请求中没有携带对应参数时使用默认值
            // keyword默认值使用空字符串，和SQL语句配合实现两种情况适配
            @RequestParam(value = "tid", defaultValue = "", required = false) Integer tid,

            @RequestParam(value = "gname", defaultValue = "", required = false) String gname,
            // pageNum默认值使用1
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,

            // pageSize默认值使用5
            @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,

            ModelMap modelMap

    ) {

        // 调用Service方法获取PageInfo对象
        PageInfo<Goods> pageInfo = goodsService.getPageInfo(tid, gname, pageNum, pageSize);

        //System.out.println("gname"+gname+"--------tname"+tid);
        // 将PageInfo对象存入模型
        modelMap.addAttribute("pageInfo", pageInfo);

        return "controller";

    }

    @ResponseBody
    @RequestMapping("queryTypeAll")
    public List<Type> queryTypeAll() {

        return goodsService.queryTypeAll();
    }

    @RequestMapping("update")
    public String update(Goods goods) {
        boolean b = false;
        if (goods.getGid() != null) {
            b = goodsService.updateGoods(goods);
        } else {
            b = goodsService.addeGoods(goods);
        }
        if (b) {
            return "redirect:getAllGoodsMutiFunction";
        } else {
            return "redirect:failure.jsp";
        }
    }

    @RequestMapping("deleteGoodsById")
    public String deleteGoodsById(@RequestParam("id") Integer id) {
        boolean b = false;
        b = goodsService.deleteGoodsById(id);
        if (b) {
            return "redirect: getAllGoodsMutiFunction";
        } else {
            return "redirect: failure.jsp";
        }
    }

    @RequestMapping("queryGoodsById")
    @ResponseBody
    public Goods queryGoodsById(@RequestParam("id") Integer id) {
        // String id = req.getParameter("id");
        Goods goods = goodsService.queryGoodsById(id);
        return goods;
    }

    @RequestMapping("queryGoodsById2")
    @ResponseBody
    public Goods queryGoodsById2(@RequestParam("id") Integer id) {
        // String id = req.getParameter("id");
        Goods goods = goodsService.queryGoodsDetailById(id);
        return goods;
    }

    //-----------------------------------------------
    @RequestMapping("uploadFile")
    public String uploadPicture(FileUpdate fileUpdate) throws IOException {
        //String goodsId = request.getParameter("goodsId");
        Goods goods = new Goods();
        System.out.println(fileUpdate + "====================================");
        // 执行文件上传
        ResultEntity<String> uploadHeaderPicResultEntity = UploadFileUtil.uploadFileToOss(
                ossProperties.getEndPoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret(),
                fileUpdate.getPicture().getInputStream(),
                ossProperties.getBucketName(),
                ossProperties.getBucketDomain(),
                fileUpdate.getPicture().getOriginalFilename());

        String result = uploadHeaderPicResultEntity.getResult();

        // 判断图是否上传成功
        if (ResultEntity.SUCCESS.equals(result)) {

            // 如果成功则从返回的数据中获取图片访问路径
            String picturePath = uploadHeaderPicResultEntity.getData();
            //goods.setGid(Integer.parseInt(goodsId));
            goods.setPicture(picturePath);
            goods.setGid(fileUpdate.getGid());
            int flag = goodsService.updateFileUri(goods);

            System.out.println(flag);

            return "redirect:getAllGoodsMutiFunction";
        } else {

            return "failure";
        }
    }

    @RequestMapping("getMoreGoodsByTid")
    public String getMoreGoodsByTid(@RequestParam("tid") String tid, Model model) {

        List<Goods> list = goodsService.getMoreGoodsByTid(tid);
        int amount = goodsService.getgetMoreGoodsByTidCount(tid);
        Type type = typeService.getTypeByTid(tid);
        model.addAttribute("goodsListWithType", list);
        model.addAttribute("amount", amount);
        model.addAttribute("type",type);
        return "category-detail";

    }

    @ResponseBody
    @RequestMapping("test")
    public String test() {
        System.out.println(ossProperties.toString());
        return ossProperties.toString();
    }

    @ResponseBody
    @RequestMapping("addTestData/{tid}/{gname}")
    public String addData(@PathVariable("tid") Integer tid, @PathVariable("gname") String gname) {

        Random random = new Random();

        int nextInt = random.nextInt(1000);
        for (int i = 1; i < 20; i++) {
            Goods goods = new Goods();
            goods.setGname(gname + i);
            goods.setPrice(new Double(nextInt * i));
            goods.setStorenum(i + 1);
            goods.setTid(tid);
            goodsMapper.insertSelective(goods);
        }

        return "success";
    }


}